#pragma once

#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <unistd.h>
#include <vector>

using task_t = std::function<void()>;
static int number = 0;

class TaskManager {
public:
    TaskManager()
    {
        srand(time(nullptr));
        tasks.push_back([] ()
    {
        std::cout << "Sub process[" << getpid() << "] 执行访问数据库任务\n" << std::endl;
    });
        tasks.push_back([] ()
    {
        std::cout << "Sub process[" << getpid() << "] 执行url解析\n" << std::endl;
    });
        tasks.push_back([] ()
    {
        std::cout << "Sub process[" << getpid() << "] 执行加密任务\n" << std::endl;
    });
        tasks.push_back([] ()
    {
        std::cout << "Sub process[" << getpid() << "] 执行数据持久化任务\n" << std::endl;
    });
    }
    int SelectTask()
    {
        return rand() % tasks.size();
    }
    void InsertTask(task_t t)
    {
        tasks[number++] = t;
    }
    void Excute(int number)
    {
        if (number > tasks.size() || number < 0)
        {
            return;
        }
        tasks[number]();
    }
    ~TaskManager()
    {}

private:
    std::vector<task_t> tasks;
};

extern TaskManager tm;

void Worker() {
    while(true) {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));
        if(n == sizeof(cmd)) {
            tm.Excute(cmd);
        } else if(n == 0) {
            std::cout << "pid: " << getpid() << " 任务结束，退出进程" << std::endl;
            break;
        }
    }
}